package com.tjec.project.projectWorkbench.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.druid.support.json.JSONUtils;
import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.constant.Constants;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.framework.security.service.TokenService;
import com.tjec.project.mdmSynchronous.api.ThreadPost;
import com.tjec.project.mdmSynchronous.dao.ProjectContractDao;
import com.tjec.project.mdmSynchronous.dao.ProjectLeaderDao;
import com.tjec.project.mdmSynchronous.service.MdmService;
import com.tjec.project.projectWorkbench.domain.BmsProject;
import com.tjec.project.projectWorkbench.mapper.BmsProjectMapper;
import com.tjec.project.system.domain.BmsAttachment;
import com.tjec.project.system.domain.BmsExpertCertification;
import com.tjec.project.system.mapper.BmsAttachmentMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.tjec.project.projectWorkbench.mapper.BmsProjectContractMapper;
import com.tjec.project.projectWorkbench.domain.BmsProjectContract;
import com.tjec.project.projectWorkbench.service.IBmsProjectContractService;
import org.springframework.util.CollectionUtils;

/**
 * 项目合同Service业务层处理
 * 
 * @author cjj
 * @date 2020-04-26
 */
@Service
public class BmsProjectContractServiceImpl implements IBmsProjectContractService 
{
    private static final Logger log = LoggerFactory.getLogger(BmsProjectContractServiceImpl.class);
    @Autowired
    private BmsProjectContractMapper bmsProjectContractMapper;

    @Autowired
    private BmsProjectMapper bmsProjectMapper;

    @Autowired
    private ProjectContractDao projectContractDao;

    @Autowired
    private BmsAttachmentMapper bmsAttachmentMapper;

    @Autowired
    private TokenService tokenService;

    @Value("${sftp.http}")
    private String http;
    @Value("${sftp.ip}")
    private String ip;
    /**
     * 查询项目合同
     * 
     * @param guid 项目合同guid
     * @return 项目合同
     */
    @Override
    public BmsProjectContract selectBmsProjectContractByGuid(String guid)
    {
        BmsProjectContract bmsProjectContract = bmsProjectContractMapper.selectBmsProjectContractByGuid(guid);
        addAttachment(bmsProjectContract);
        return bmsProjectContract;
    }

    //项目合同附件
    private void addAttachment(BmsProjectContract bmsProjectContract){
        ArrayList<String> attIds = new ArrayList<>();
        if(!CollectionUtils.isEmpty(bmsProjectContract.getBmsAttachments())){
            for (BmsAttachment bmsAttachment : bmsProjectContract.getBmsAttachments()) {
                bmsAttachment.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + bmsAttachment.getStoragePath());
                attIds.add(bmsAttachment.getGuid());
            }
        }
        bmsProjectContract.setAttachmentIds(attIds);
    }

    /**
     * 查询项目合同列表
     * 
     * @param bmsProjectContract 项目合同
     * @return 项目合同
     */
    @Override
    public List<BmsProjectContract> selectBmsProjectContractList(BmsProjectContract bmsProjectContract)
    {
        List<BmsProjectContract> list = bmsProjectContractMapper.selectBmsProjectContractList(bmsProjectContract);
        for (BmsProjectContract projectContract : list) {
            addAttachment(projectContract);
        }
        return list;
    }

    /**
     * 新增项目合同
     * 
     * @param bmsProjectContract 项目合同
     * @return 结果
     */
    @Override
    public int insertBmsProjectContract(BmsProjectContract bmsProjectContract)
    {
        bmsProjectContract.setCreateTime(DateUtils.getNowDate());
        bmsProjectContract.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        if(null==bmsProjectContract.getGuid()||("").equals(bmsProjectContract.getGuid())){
            bmsProjectContract.setGuid(UUID.randomUUID().toString());
        }
        return bmsProjectContractMapper.insertBmsProjectContract(bmsProjectContract);
    }

    /**
     * 修改项目合同
     * 
     * @param bmsProjectContract 项目合同
     * @return 结果
     */
    @Override
    public int updateBmsProjectContract(BmsProjectContract bmsProjectContract)
    {
        bmsProjectContract.setUpdateTime(DateUtils.getNowDate());
        bmsProjectContract.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        //更新专家持证情况、上传附件，每次删除原来的，添加最新的
        if(com.tjec.common.utils.StringUtils.isNotBlank(bmsProjectContract.getGuid())){
            bmsAttachmentMapper.updateBmsAttachmentByBizId(new String[]{bmsProjectContract.getGuid()}, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        }
        if(!CollectionUtils.isEmpty(bmsProjectContract.getAttachmentIds())){
            bmsAttachmentMapper.updateBmsAttachmentByGuidsUpdateBiz(bmsProjectContract.getAttachmentIds(), bmsProjectContract.getGuid(), AttachmentConstants.PROJECT_CONTRACT, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        }
        return bmsProjectContractMapper.updateBmsProjectContract(bmsProjectContract);
    }

    /**
     * 批量删除项目合同
     * 
     * @param guids 需要删除的项目合同ID
     * @return 结果
     */
    @Override
    public int deleteBmsProjectContractByGuids(String[] guids)
    {
        return bmsProjectContractMapper.deleteBmsProjectContractByGuids(guids);
    }

    /**
     * 删除项目合同信息
     * 
     * @param guid 项目合同guid
     * @return 结果
     */
    @Override
    public int deleteBmsProjectContractByGuid(String guid)
    {
        return bmsProjectContractMapper.deleteBmsProjectContractByGuid(guid);
    }
    /**
     *
     *@describe
     *@params [globalId, timestamp] 项目合同id   时间戳
     *@return int
     *@author VillWang
     *@date 2020/5/14
     *@other globalId  为空 timestamp  不为空   为定时同步  globalId不为空为手动同步
     *
     */
    @Override
    public int synchronous(String globalId, long timestamp) {
        String projectId = null;
        try {
            List<Map<String, Object>> list =projectContractDao.getProjectContractList(globalId,timestamp);
            List<BmsProjectContract>  lists= new ArrayList<>();
            //请求没有数据，默认获取测试表中数据
            if(CollectionUtils.isEmpty(list)){
               /* BmsProject bmsProject = new BmsProject();
                bmsProject.setCode(globalId);
                List<BmsProject>  bmsProjects = bmsProjectMapper.selectBmsProjectList(bmsProject);
                if(!CollectionUtils.isEmpty(bmsProjects)){
                    projectId = bmsProjects.get(0).getGuid();
                }
                lists = bmsProjectContractMapper.getSimulatedData();*/
            }else{
                lists= dealWith(list);
            }
            //批量
            //insertThirdData(lists);
            for (BmsProjectContract bmsProjectContract:lists) {
                String globalId2=bmsProjectContract.getGlobalId();
                BmsProjectContract  bms=  bmsProjectContractMapper.selectBmsProjectContractByGlobalId(globalId2);
                //判断该数据是否是已存在 已存在更新，没有插入
                if(bms==null||bms.equals("")){
                  //不存在添加
                    bmsProjectContract.setGuid(UUID.randomUUID().toString());
                    //bmsProjectContract.setProjectId(projectId);
                    bmsProjectContractMapper.insertBmsProjectContract(bmsProjectContract);
                }else {
                    //更新
                    bms.setProjectId(bmsProjectContract.getProjectId());
                    bms.setName(bmsProjectContract.getName());
                    bms.setCode(bmsProjectContract.getCode());
                    bms.setSignDate(bmsProjectContract.getSignDate());
                    bms.setNature(bmsProjectContract.getNature());
                    bms.setFeeCollectionTerms(bmsProjectContract.getFeeCollectionTerms());
                    bms.setServerTerms(bmsProjectContract.getServerTerms());
                    bms.setServiceContentRemark(bmsProjectContract.getServiceContentRemark());
                    bms.setSigningUnitRemark(bmsProjectContract.getSigningUnitRemark());
                    bms.setProjectOverviewRemark(bmsProjectContract.getProjectOverviewRemark());
                    bms.setOtherRemark(bmsProjectContract.getOtherRemark());
                    bms.setTimeStamp(bmsProjectContract.getTimeStamp());
                    bmsProjectContractMapper.updateBmsProjectContract(bms);
                }

            }
        } catch (Exception e) {
            log.error("项目合同同步失败，详细信息："+e);
            e.printStackTrace();
        }
        return 1;
    }
    /**
     * 插入第三方数据
     *
     * @param list
     * @param globalIdList
     */
    //批量插入，分页数量
    final int INSERT_BATCH_DIVISOR = 50;
    private void insertThirdData(List<BmsProjectContract> insertList) {
        //要插入的数据
        int size = insertList.size();
        //分页插入数据
        int times = size / INSERT_BATCH_DIVISOR;
        int remain = size % INSERT_BATCH_DIVISOR;
        //完整一页
        for (int i = 0; i < times; i++) {
            List<BmsProjectContract> subList = insertList.subList(i * INSERT_BATCH_DIVISOR, (i + 1) * INSERT_BATCH_DIVISOR);
            bmsProjectContractMapper.batchInsertBmsProjectContent(subList);
        }
        //剩余部分
        if (remain > 0) {
            List<BmsProjectContract> subList = insertList.subList(INSERT_BATCH_DIVISOR * times, insertList.size());
            bmsProjectContractMapper.batchInsertBmsProjectContent(subList);
        }
    }
    /**
     *
     *@describe 获取最大时间戳
     *@params []
     *@return int
     *@author VillWang
     *@date 2020/6/12
     *@other
     *
     */
    @Override
    public long selectMaxTime() {
        long max = bmsProjectContractMapper.selectMaxTime();
        return max;
    }

    /**
     *
     *@describe mdm接口返回值处理
     *@params [json]  json数据
     *@return java.util.List<com.tjec.project.projectWorkbench.domain.BmsProjectContract>
     *@author VillWang
     *@date 2020/5/14
     *@other
     *
     */
    public List<BmsProjectContract> dealWith( List<Map<String, Object>> list) {
        List<BmsProjectContract> bmsProjectContractArrayList=new ArrayList<BmsProjectContract>();
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
        for (Map<String, Object> map:list) {
            BmsProjectContract bmsProjectContract =  new BmsProjectContract();
            bmsProjectContract.setGlobalId((String) map.get("globalId"));
            bmsProjectContract.setProjectId((String) map.get("code"));
//            bmsProjectContract.setCode((String) map.get("code"));
            String coprojectId=(String) map.get("coprojectId");
            bmsProjectContract.setCode(coprojectId);
            bmsProjectContract.setName((String) map.get("name"));
            String date=(String)map.get("signDate");
            if(StringUtils.isNotBlank(date)){
                try {
                    bmsProjectContract.setSignDate(sdf.parse(date));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            bmsProjectContract.setNature((String) map.get("nature"));
            bmsProjectContract.setFeeCollectionTerms((String) map.get("feeCollectionTerms"));
            bmsProjectContract.setServerTerms((String) map.get("serverTerms"));
            bmsProjectContract.setServiceContentRemark((String) map.get("serviceContentRemark"));
            bmsProjectContract.setSigningUnitRemark((String) map.get("signingUnitRemark"));
            bmsProjectContract.setProjectOverviewRemark((String) map.get("projectOverviewRemark"));
            bmsProjectContract.setOtherRemark((String) map.get("otherRemark"));
            bmsProjectContract.setTimeStamp(String.valueOf(map.get("timestamp")));
            String scopeOf=(String) map.get("scopeOf");
            if(scopeOf!=null&&scopeOf.contains("外部统计")){
                bmsProjectContractArrayList.add(bmsProjectContract);
            }
        }
        return bmsProjectContractArrayList;
    }
}
